package com.littlebee.storysuper.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.littlebee.storysuper.R;
import com.littlebee.storysuper.common.sharePrefUtils.SharePrefUtil;
import com.littlebee.storysuper.tcp.SendCmdBean;
import com.littlebee.storysuper.tcp.TcpClientUtil;
import com.littlebee.storysuper.utils.Constant;
import com.littlebee.storysuper.utils.GsonUtils;
import com.littlebee.storysuper.utils.LogUtil;
import com.littlebee.storysuper.utils.ToastUtil;
import com.littlebee.storysuper.utils.Utils;
import com.tjstudy.tcplib.ResponseCallback;
import com.zss.library.activity.BaseActivity;
import com.zss.library.toolbar.CommonToolbar;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Locale;

import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;

/**
 * Created by liaoyong on 17/11/2017.
 */

public class VoiceCallingActivity extends BaseActivity
    implements View.OnClickListener{
    private RtcEngine mRtcEngine;// Tutorial Step 1
    private Button btn_call;
    private TextView tv_status;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_voicecalling;
    }

    @Override
    public void setTopBar() {
        super.setTopBar();
        setStatusBarColor(R.color.module_video_bg);
        CommonToolbar toolbar = getToolbar();
        toolbar.setBgRes(R.color.module_video_bg);
        toolbar.setTitle(getString(R.string.online_calling_txt));
    }

    @Override
    public void initView() {
        super.initView();
        btn_call = (Button) findViewById(R.id.btn_call);
        btn_call.setOnClickListener(this);
        tv_status = (TextView) findViewById(R.id.tv_status);

        TcpClientUtil.getInstance().init();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        initAgoraEngineAndJoinChannel();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_call) {
            //start tcp server
            LogUtil.d("liaoyong:click call btn..");
            SendCmdBean sendCmdBean = new SendCmdBean();
            sendCmdBean.msgdesc = "mother connect";
            sendCmdBean.mamaid = Utils.getUserEntry().getMobile();
            TcpClientUtil.getInstance().sendMessage(SendCmdBean.CMD_CONNECT_BABY_TYPE, responseCallback);
            tv_status.setText("start calling...");
            mRtcEngine.setEnableSpeakerphone(true);
        }
    }

    // Tutorial Step 7
    public void onLocalAudioMuteClicked(View view) {
//        ImageView iv = (ImageView) view;
//        if (iv.isSelected()) {
//            iv.setSelected(false);
//            iv.clearColorFilter();
//        } else {
//            iv.setSelected(true);
//            iv.setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY);
//        }
//
//        mRtcEngine.muteLocalAudioStream(iv.isSelected());
    }

    private void initAgoraEngineAndJoinChannel() {
        initializeAgoraEngine();     // Tutorial Step 1
        joinChannel();               // Tutorial Step 2
    }

    // Tutorial Step 2
    private void joinChannel() {
        SharedPreferences sharedPreferences;
        sharedPreferences = getSharedPreferences(Constant.appName, Context.MODE_PRIVATE); //私有数据
        String channelName = sharedPreferences.getString(MainActivity.HASBINDDEVICEID, "");
        mRtcEngine.joinChannel(null, channelName, "Extra Optional Data", 0); // if you do not specify the uid, we will generate the uid for you
    }

    // Tutorial Step 5
    public void onSwitchSpeakerphoneClicked(View view) {
        LogUtil.d("liaoyong: onSwitchSpeakerphoneClicked");
        ImageView iv = (ImageView) view;
        if (iv.isSelected()) {
            iv.setSelected(false);
            iv.clearColorFilter();
        } else {
            iv.setSelected(true);
            iv.setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY);
        }
        mRtcEngine.setEnableSpeakerphone(view.isSelected());
    }

    // Tutorial Step 3
    public void onEncCallClicked(View view) {
        finish();
    }

    // Tutorial Step 1
    private void initializeAgoraEngine() {
        try {
            mRtcEngine = RtcEngine.create(getBaseContext(), getString(R.string.agora_app_id), mRtcEventHandler);
        } catch (Exception e) {
            LogUtil.d("liaoyong:init speak error..." );
            throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
        }
    }

    private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() { // Tutorial Step 1

        @Override
        public void onUserOffline(final int uid, final int reason) { // Tutorial Step 4
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    onRemoteUserLeft(uid, reason);
                }
            });
        }

        @Override
        public void onUserMuteAudio(final int uid, final boolean muted) { // Tutorial Step 6
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    onRemoteUserVoiceMuted(uid, muted);
                }
            });
        }
    };

    // Tutorial Step 4
    private void onRemoteUserLeft(int uid, int reason) {
        ToastUtil.displayShortToast("onRemoteUserLeft");
//        showLongToast(String.format(Locale.US, "user %d left %d", (uid & 0xFFFFFFFFL), reason));
//        View tipMsg = findViewById(R.id.quick_tips_when_use_agora_sdk); // optional UI
//        tipMsg.setVisibility(View.VISIBLE);
    }

    // Tutorial Step 6
    private void onRemoteUserVoiceMuted(int uid, boolean muted) {
        ToastUtil.displayShortToast(String.format(Locale.US, "user %d muted or unmuted %b", (uid & 0xFFFFFFFFL), muted));
    }


    private ResponseCallback responseCallback = new ResponseCallback() {
        @Override
        public void onRec(Object message) {
            LogUtil.d("recv:" + message.toString());
//            ToastUtil.displayLongToast("recv:" + message.toString());
            SendCmdBean sendCmdBean = GsonUtils.getObjFromJSON(message.toString(), SendCmdBean.class);
            if (sendCmdBean.msgid == SendCmdBean.CMD_RESPONSE_TYPE) {
                ToastUtil.displayLongToast("recv response" );
                tv_status.setText("send connect success");
            }

        }

        @Override
        public void onFail(Throwable throwable) {

        }
    };
}
